import os
import subprocess
from datetime import datetime
import re
import json
import hashlib

def exec_bash(list):
	rs = subprocess.run(list,stdout=subprocess.PIPE)
	# print(rs)
	txt = rs.stdout.decode("utf-8")
	return txt
	
def exec_bash_to_lines(list):
	rs = subprocess.run(list,stdout=subprocess.PIPE)
	# print(rs)
	# 检查命令是否成功
	if rs.returncode != 0:
		return []
	    #print("命令执行失败:", result.stderr)
	else:
	    # 遍历输出的每一行
	    lines = rs.stdout.decode("utf-8").strip().split('\n')
	    
	    return lines
		
def del_cangku_info(logtxt):
	pattern = r'(code\.88shike\.com[^\s]+)'
	# matches = re.findall(pattern, logtxt)
	# print(matches)
	logtxt = re.sub(pattern, '仓库路径', logtxt)
	# print(f"修改日志记录2:{history_log}")
	return logtxt
	
def get_cangku_no(url):
	pattern = r'/r/(PJ[^.]+)'
	matches = re.findall(pattern, url)
	# print(matches)
	unique_list = list(set(matches))
	# print(unique_list)
	if len(unique_list) > 1:
		print(unique_list)
		print("检查到多个项目编号")
		exit(0)
	elif len(unique_list) == 0:
		print("未检查到项目编号")
		exit(0)
	
	return unique_list[0]

def calculate_file_md5(file_path):
    # 创建 MD5 对象
    md5_hash = hashlib.md5()
    
    # 以二进制模式打开文件
    with open(file_path, "rb") as f:
        # 分块读取文件内容
        for chunk in iter(lambda: f.read(4096), b""):
            md5_hash.update(chunk)
    
    return md5_hash.hexdigest()

# 获取当前脚本的完整路径tool
# 获取当前脚本的完整路径
current_file_path = __file__
toolfile_md5 = calculate_file_md5(current_file_path)
print(f"文件的 MD5 哈希值: {toolfile_md5}")

# 判断项目类型
#git remote -v
current_url = exec_bash(['git','remote','-v'])
current_project_num = get_cangku_no(current_url)

print(f"当前项目编号:[{current_project_num}]")
projects = {
	"PJ2203240223":"专家后台",
	"PJ2204240223":"会员官网",
	"PJ2206240829":"SAAS管理系统",
	"PJ2208241111":"测评报告",
	"PJ2209241125":"H5版本(移动端)",
	"PJ2210241205":"APP(IOS/Andorid)",
	"PJ2211241205":"微信小程序",
}

if current_project_num not in projects:
	print("不支持的项目.")
	exit(0)

appId = ""
appName = ""
domainName = ""
configPath = ""
if current_project_num == "PJ2211241205":
	print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
	print( f"配置《{projects[current_project_num]}》请选择一个实例项目")
	print( "1. 报考管家")
	print( "2. 金榜如愿")
	print( "3. 志愿星")
	print( "4. 大民唐邦教育")
	print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
	configPath = "common/manager/xcxinfo.js"
	while True:
		user_input = input("请输入内容（输入 'exit' 结束）: ")
		if user_input.lower() == 'exit':
			exit(0)
		number = int(user_input)
		if number == 1:
			print("配置:报考管家")
			appId="wx04a4ad5325758043"
			appName="报考管家"
			domainName="https://h5.huixinshengxue.com"
		elif number == 2:
			print("配置:金榜如愿")
			appId="wxc6791a5cb7eebdb5"
			appName="金榜如愿"
			domainName="https://zym.jinbangruyuan.com"
		elif number == 3:
			print("配置:志愿星")
			appId="wx04a4ad5325758043"
			appName="志愿星"
			domainName="https://xcx.chatgk.com"
		elif number == 4:
			print("配置:大民唐邦教育")
			appId="未配置"
			appName="大民唐邦教育"
			domainName="https://dmtm.chatgk.cn"
		else:
			continue
		
		break
elif current_project_num == "PJ2210241205":
	print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
	print( f"配置《{projects[current_project_num]}》请选择一个实例项目")
	print( "1. CHAT高考")
	print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
	
	configPath = ""
	while True:
		user_input = input("请输入内容（输入 'exit' 结束）: ")
		if user_input.lower() == 'exit':
			exit(0)
		number = int(user_input)
		if number == 1:
			print("配置:CHAT高考")
			appId="xxxx"
			appName="CHAT高考"
			domainName="https://appv2.chatgk.com"
		else:
			continue
		break
elif current_project_num == "PJ2209241125":
	print("配置:测评报告")
	appId="2209"
	appName=projects[current_project_num]
	domainName="无需配置"
	print("暂不支持")
	exit(0)
elif current_project_num:
	# VUE 项目....
	print(f" VUE 配置:{projects[current_project_num]}")
	appId=current_project_num[2:6]
	appName=projects[current_project_num]
	domainName="无需配置"
	configPath = "src/api/projmanager.js"
	input("请Enter 开始配置: ")
	
	
# 获取当前分支名并保存到变量
# git rev-parse --abbrev-ref HEAD
current_branch = exec_bash(['git','rev-parse','--abbrev-ref','HEAD'])
current_branch = current_branch[:len(current_branch) - 1]
print(f"当前项目分支:[{current_branch}]")


# 检查本地是否有未提交的修改
# git status --porcelain
current_modify = 0
current_modify_txt = exec_bash(['git','status','--porcelain'])
# print(current_modify_txt)
if current_modify_txt is not None and len(current_modify_txt) > 0:
	current_modify = 1
print(f"代码修改状态:[{current_modify}]")

# 检查是否有未推送的提交
# git rev-list --count HEAD
# git rev-list --count @{u}
unpush_status = 0
rst = exec_bash(['git','rev-list','--count','HEAD'])
if rst is not None and len(rst) > 0:
	unpush_status = 1
else:
	rst = exec_bash(['git','rev-list','--count','@{u}'])
	if rst is not None and len(rst) > 0:
		unpush_status = 1
print(f"代码PUSH状态:[{unpush_status}]")


# 后30条修改日志
#git log -n 30 --pretty=format:'"%an %h %f %ad => %s" ' --date=format:"%y-%m-%d %H:%M:%S" --numstat | awk 'BEGIN {commit_msg=""; file_count=0} /^[0-9]/ {file_count++} /^"[^"]+"/ {if (commit_msg != "") {print commit_msg, file_count}; commit_msg=$0; file_count=0} END {if (commit_msg != "") {print commit_msg, file_count}}'
# git log -n 30 --pretty=format:'"%an %h %f %ad=>%s"', --date format:"%y-%m-%d %H:%M:%S"
# history_log = exec_bash(['git','log','-n','30','--pretty=format:%an %h  %ad=>%s,','--date=format:%y-%m-%d %H:%M:%S'])
# print(rst)
# history_log = history_log[:len(history_log)-1]

# 替换 '.' 为 '!'
# pattern = r'(code\.88shike\.com[^\s]+)'
# matches = re.findall(pattern, history_log)
# print(matches)
# history_log = re.sub(pattern, '仓库路径', history_log)
# print(f"修改日志记录2:{history_log}")

# 后30条修改日志
history_log_tag = exec_bash(['git','log','-n','30','--pretty=format:"%h",'])

history_log_tag = history_log_tag[:len(history_log_tag) - 1]
history_log_tag = f"[{history_log_tag}]"
# print(history_log_tag)
history_log_tag = json.loads(history_log_tag)
# print(history_log_tag)
num=0
tag_history = []
for tag in history_log_tag:
	num+=1
	print(f"-----------------------标签:{tag} ---------[{len(history_log_tag)}/{num}]")
	
	#获取用户
	#git log -n 1 c52dcd0 --pretty=format:%an
	tag_user = exec_bash(['git','log','-n','1',tag,'--pretty=format:%an'])
	tag_user = tag_user.replace("\\","\\\\")
	print(f"修改者:{tag_user}")
	
	#获取时间
	#git log -n 1 c52dcd0 --pretty=format:%an
	tag_time = exec_bash(['git','log','-n','1',tag,'--pretty=format:%ad','--date=format:%y-%m-%d %H:%M:%S'])
	print(f"修改者:{tag_time}")
	# 定义时间格式
	time_format = "%y-%m-%d %H:%M:%S"
	# 将时间字符串转换为 datetime 对象
	time1 = datetime.strptime(tag_time, time_format)
	time2 = datetime.strptime("24-12-07 00:00:00", time_format)
	if time2 > time1:
		break
	
	#获取日志
	#git log -n 1 c52dcd0 --pretty=format:%an
	tag_remark = exec_bash(['git','log','-n','1',tag,'--pretty=format:%s'])
	tag_remark = del_cangku_info(tag_remark)
	print(f"修改日志:{tag_remark}")
	tag_remark = tag_remark.replace("\\","\\\\")
	tag_remark = tag_remark.replace("'","\\'")
	
	
	#获取修改数量
	#>git log -n 1 9ff40e6 --numstat
	numstats = exec_bash_to_lines(['git','log','-n','1',tag,'--numstat'])
	#print(f"修改数量:{numstatss}")
	# 提取 numstat 行的信息
	tag_nums=[]
	for line in numstats:
		if line:  # 确保行不为空
			parts = line.split('\t')
			if len(parts) == 3:  # 确保符合 numstat 格式：增加行数 删除行数 文件名
				added_lines = parts[0]
				deleted_lines = parts[1]
				filename = parts[2]
				
				info = {}
				info["file"] = filename
				info["add"] = added_lines
				info["del"] = deleted_lines
				
				tag_nums.append(info)
				
				# 打印结果
				# print(f"文件: {filename}, 新增行数: {added_lines}, 删除行数: {deleted_lines}")
	print(f"修改数量:{len(tag_nums)}")			
	# print(f"修改明细:{tag_nums}")
	#,"files":tag_nums
	item={"tag":tag,"user":tag_user,"time":tag_time,"log":tag_remark,"filenums":len(tag_nums)}
	
	tag_history.append(item)

# 最后一次提交标签
# git log -n 1 --pretty=format:'%h'
last_log = exec_bash(['git','log','-n','1','--pretty=format:%h'])
# print(rst)
# last_log = last_log[:len(last_log)-1]
print(f"最后一次提交标签:{last_log}")

tagver = f"{current_branch}_{current_modify}_{unpush_status}_{last_log}"
print(f"发布标签:{tagver}")

# 获取当前用户
# git config user.name
dev_user = exec_bash(['git','config','user.name'])
dev_user = dev_user[:len(dev_user)-1]
dev_user = dev_user.replace("\\","\\\\")
print(f"当前用户:[{dev_user}]")

# curent_time=$(date +"%Y-%m-%d %H:%M:%S")
# dev_user=$(git config user.name)

# 获取当前系统时间
currenttime = datetime.now()

# 格式化时间为 'y-m-d h:m:s'
curent_time = currenttime.strftime("%y-%m-%d %H:%M:%S")

print("当前系统时间:", curent_time)


if dev_user is None or len("{dev_user}") <= 0:
	print("开发者获取失败.")
	exit(0)
if curent_time is None or len("{curent_time}") <= 0:
	print("当前时间获取失败.")
	exit(0)

if appId is None or len("{appId}") <= 0:
	print("APPID 未配置.")
	exit(0)

if appName is None or len("{appName}") <= 0:
	print("APP 名称 未配置.")
	exit(0)

if domainName is None or len("{domainName}") <= 0:
	print("APP 访问域名 未配置.")
	exit(0)
tag_history_txt=""
for item in tag_history:
	#[{'tag': '1bac6fa0', 'user': 'zhangyao', 'time': '24-12-13 11:23:04', 'log': 'fix: 缓存', 'filenums': 1}
	itemData = f"""{{
		tag:'{item["tag"]}',
		user:'{item["user"]}',
		time:'{item["time"]}',
		log:'{item["log"]}',
		filenums:{item["filenums"]}
	}}"""
	if len(tag_history_txt) <= 0:
		tag_history_txt = itemData
	else:
		tag_history_txt += f",{itemData}"

# export const projmanager = {
configData = f"""export const projmanager = {{
	toolsign:'{toolfile_md5}',
	user:'{dev_user}',
	publish_time:'{curent_time}',
	appId:'{appId}',
	name:'{appName}',
	domainName:'{domainName}',
	lasttag:'{tagver}',
	historylog:[{tag_history_txt}]
}}"""

#historylog:'{tag_history}'
#configData = json.dumps(configData, ensure_ascii=False,indent=4)
print(configData)
# 使用 'with' 语句打开文件以保证正确关闭
with open(configPath, "w", encoding='utf-8') as file:
    # 将字符串写入文件
    file.write(configData)
exit(0)


# 使用 'with' 语句打开文件以保证正确关闭
with open("common/manager/xcxinfo.js", "w") as file:
    # 将字符串写入文件
    file.write(configData)

# echo "export default {  user:'$dev_user',publish_time:'$curent_time',appId:'$appId',  name: '$appName',    domainName: '$domainName',historylog:[$history_log], lasttag:'$tagver'}" > common/manager/xcxinfo.js





# echo "export default {  user:'$dev_user',publish_time:'$curent_time',appId:'$appId',  name: '$appName',    domainName: '$domainName',historylog:[$history_log], lasttag:'$tagver'}" > common/manager/xcxinfo.js

# echo "a.--------------- common/manager/xcxinfo.js 文件内容 >>>>>>>>>>>>>>>>>>"
# cat common/manager/xcxinfo.js
# echo ""

# #echo "b.--------------- manifest.json 文件配置结果 >>>>>>>>>>>>>>>>>>"
# echo "开始修改 manifest APP名称:$appName"
# #echo "$appName"

# cmdtxt="sed -i '' 's/\"name\": *\"[^\"]*\"/\"name\": \"$appName\"/' manifest.json"
# #echo "$cmdtxt"
# eval $cmdtxt

# cmdtxt="grep \"\\\"name\\\": *\\\"$appName\\\"\" manifest.json | sed -n 's/.*\"\([^\"]*\)\".*/\1/p'"
# #echo "$cmdtxt"
# rst=$(eval $cmdtxt)
# #echo "[$rst] | [$appName]"
# if [ "$rst" != "$appName" ]; then
# #if $rst != $appName; then
# 	echo "修改manifest -- APP名称 失败."
# 	exit
# fi
# echo "成功修改 manifest APP名称:$appName"


# echo "开始修改 pages首页标题:$appName"
# cmdtxt="sed -i '' 's/\"navigationBarTitleText\": *\"[^\"]*\", \/\/小程序首页标题,本行格式不要修改,重要重要./\"navigationBarTitleText\": \"$appName\", \\/\\/小程序首页标题,本行格式不要修改,重要重要./' pages.json"
# #echo "$cmdtxt"
# rst=$(eval $cmdtxt)
# cmdtxt="grep \"\\\"navigationBarTitleText\\\": *\\\"$appName\\\", \\/\\/小程序首页标题,本行格式不要修改,重要重要.\" pages.json | sed -n 's/.*\"\([^\"]*\)\".*/\1/p'"
# #echo "$cmdtxt"
# rst=$(eval $cmdtxt)
# #echo "[$rst] | [$appName]"
# if [ "$rst" != "$appName" ]; then
# #if $rst != $appName; then
# 	echo "修改pages -- 主页标题失败."
# 	exit
# fi
# echo "成功修改 pages首页标题:$appName"

# echo ""
# echo "c.************发布/调试微信小程序需要在微信开发者工具修改为微信小程序的appID:$appId**********"
# echo "c.************发布/调试微信小程序需要在微信开发者工具修改为微信小程序的appID:$appId**********"
# echo "c.************发布/调试微信小程序需要在微信开发者工具修改为微信小程序的appID:$appId**********"
# echo ""
# echo "微信小程序appID:$appId"
# echo "微信小程序名称:$appName"
# echo "微信小程序接口域名:$domainName"
# echo "微信小程序发布时间:$curent_time"

# echo ""
# echo '配置完成'
# read -p "回车键推出......" choice




